<template>
  <div>
    <button @click="startScreenCapture">开始屏幕捕获</button>
    <button @click="stopScreenCapture" v-if="mediaStream">停止屏幕捕获</button>
    <video v-if="mediaStream" ref="video" autoplay playsinline></video>
  </div>
</template>

<script lang="ts">
import { ref } from 'vue';

// 定义一个名为 ScreenCapture 的 Vue 组件
export default {
  name: 'ScreenCapture',
  setup() {
    const mediaStream = ref<MediaStream | null>(null);
    const videoRef = ref<HTMLVideoElement | null>(null);

    // 开始屏幕捕获的方法
    const startScreenCapture = async () => {
      try {
        const stream = await navigator.mediaDevices.getDisplayMedia({ video: true });
        mediaStream.value = stream;
        if (videoRef.value) {
          videoRef.value.srcObject = stream;
        }
        stream.getTracks().forEach(track => {
          track.onended = () => {
            console.log('屏幕捕获已结束');
          };
        });
      } catch (err) {
        console.error('无法获取屏幕内容:', err);
      }
    };

    // 停止屏幕捕获的方法
    const stopScreenCapture = () => {
      if (mediaStream.value) {
        mediaStream.value.getTracks().forEach(track => track.stop());
        mediaStream.value = null;
      }
    };

    return {
      mediaStream,
      videoRef,
      startScreenCapture,
      stopScreenCapture,
    };
  },
};
</script>

<style scoped>
button {
  margin: 20px;
  padding: 10px 20px;
}
</style>